//
//  ComposeViewController.swift
//  sinaWeibo
//
//  Created by liii on 16/8/6.
//  Copyright © 2016年 liii. All rights reserved.
//

import UIKit
import SVProgressHUD
import SnapKit

class ComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }

    private func setupUI() {
        
        // 设置view背景色，替代透明效果
        view.backgroundColor = UIColor.whiteColor()
        
        // 自定义导航栏
        setNavigationBar()
        
        // 自定义输入框
        setTextView()
        
        // 底部工具条
        setToolBar()
        
        // 注册通知，监听键盘显示和隐藏
        defaultCenter.addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        // 添加图片选择器
        setPictureSelectorVC()
        
        // 把工具条移动到最上层
        self.view.bringSubviewToFront(toolBar)
    }
    
    // 处理通知
    @objc private func keyboardChanged(notification: NSNotification) {
        print(notification)
        
        // 获取动画时间，及键盘移动结束后的frame
        let duration = (notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let rect = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        // 随着键盘的显示和隐藏，toolBar偏移量相对于屏幕计算
        let offset = -screenHeight + rect.origin.y
        
        // 添加动画效果
        UIView.animateWithDuration(duration) { () -> Void in
            // 更新约束
            self.toolBar.snp_updateConstraints { (make) -> Void in
                // 收集约束
                make.bottom.equalTo(offset)
            }
            // 刷新视图
            self.view.layoutIfNeeded()
        }
    }
    
    // 移除通知
    deinit {
        defaultCenter.removeObserver(self)
    }
    
    // navagitionItem.titleView
    private lazy var myView: UIView = UIView(frame: CGRectMake(0, 0, screenWidth, 40))
    // titleView.titleLabel
    private lazy var titleLabel: UILabel = UIFactory.labelWithText("发布微博", fontSize: 18, textColor: UIColor.grayColor())
    // titleView.nameLabel
    private lazy var nameLabel: UILabel = UIFactory.labelWithText(UserAccount.sharedAccount.name ?? "", fontSize: 14, textColor: UIColor.orangeColor())
    // 输入框
    private lazy var textView: UITextView = UIFactory.textViewWithText(nil, fontSize: 14)
    // 占位文本
    private lazy var placeholderLabel: UILabel = UIFactory.labelWithText("测试数据...", fontSize: 14, textColor: UIColor.grayColor())
    // toolBar有默认高度（44）
    private lazy var toolBar: UIToolbar = UIToolbar()
    // 图片选择器
    private lazy var pictureSelectorVC: PictureSelectorController = PictureSelectorController()
}

// 处理业务逻辑
extension ComposeViewController {
    // 关闭控制器
    @objc private func close() {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    // 发布微博
    @objc private func send() {
        // 参数
        var urlString = "2/statuses/update.json"
        guard let token = UserAccount.sharedAccount.access_token else {
            print("用户未登陆，或登陆过期")
            return
        }
        let parameters = ["access_token" : token, "status" : textView.text]
        
        
        if pictureSelectorVC.imageList.count != 0 {
            
            // 发布图片微博
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            let imageData = UIImagePNGRepresentation(pictureSelectorVC.imageList.first!)!
            
            HTTPClient.sharedClient.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
                    // 单图上传
                    /*
                    将要上传的文件拼接到formData中
                    1.data: 表示要上传文件的二进制数据
                    2.name: 服务器接收的字段名称 pic
                    3.fileName: 服务器存储名称，可随意，新浪会做防重处理
                    4.mimeType: 服务器存储类型
                    */
                    formData.appendPartWithFileData(imageData, name: "pic", fileName: "sinaWeibo", mimeType:"application/octet-stream")
                
                    // 多图上传
                    for image in self.pictureSelectorVC.imageList {
                        let data = UIImagePNGRepresentation(image)!
                        formData.appendPartWithFileData(data, name: "pic", fileName: "anyImageName", mimeType:"application/octet-stream")
                    }
                }, success: { (_, result) -> Void in
                    // 发布成功
                    print(result)
                    self.dismissViewControllerAnimated(true, completion: nil)
                }, failure: { (_, error) -> Void in
                    // 发布失败
                    print(error)
            })
        } else {
            // 发布文字微博
            HTTPClient.sharedClient.requestJSONDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
                
                // 发布失败
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("发布失败，请检查网络！")
                    return
                }
                // 发布成功
                SVProgressHUD.showSuccessWithStatus("发布成功！")
                self.close()
            }
        }
        
    }
    
    // 图片
    @objc private func selectPicture() {
        
        UIView.animateWithDuration(0.5) { () -> Void in
            self.pictureSelectorVC.view.snp_updateConstraints { (make) -> Void in
                make.height.equalTo(screenHeight / 3 * 2)
            }
            self.view.layoutIfNeeded()
        }
    }
    // 表情
    @objc private func selectEmoticon() {
        print(__FUNCTION__)
    }

    private func setNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "send")
        
        // 禁用“发布”按钮
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 自定义titleView
        navigationItem.titleView = myView
        
        // 添加子控件
        myView.addSubview(titleLabel)
        myView.addSubview(nameLabel)
        
        // 布局子控件
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(myView.snp_top)
            make.centerX.equalTo(myView.snp_centerX)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleLabel.snp_bottom)
            make.centerX.equalTo(myView.snp_centerX)
        }
    }
    
    // 添加并布局textView
    private func setTextView() {
        
        view.addSubview(textView)
        textView.addSubview(placeholderLabel)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(screenHeight / 3)
        }
        placeholderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(8)
            make.left.equalTo(textView).offset(5)
        }
        
        // 监听文本框，处理键盘
        textView.delegate = self
        textView.keyboardDismissMode = .OnDrag
        textView.alwaysBounceVertical = true
    }
    
    // 添加并布局底部工具条
    private func setToolBar() {
        
        view.addSubview(toolBar)
        
        toolBar.backgroundColor = UIColor.greenColor()
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(view)
        }
        
        // 设置数据源
        var items = [UIBarButtonItem]()
        // 按钮图片数组
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_add_background"]]
        
        
        // 添加到弹簧，实现等分布局，.FlexibleSpace（可伸缩弹簧）
        let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
//        items.append(space)
        
        // 创建按钮, 添加弹簧
        for item in itemSettings {
            // 设置按钮图片
            let imageName = item["imageName"]
            let btn = UIFactory.buttonWithImage(imageName, backgroundImage: nil)
            
            // 设置监听事件
            if let actionName = item["actionName"] {
                btn.addTarget(self, action: Selector(actionName), forControlEvents: .TouchUpInside)
            }
            
            // 自定义UIBarButtonItem
            let bbtni = UIBarButtonItem(customView: btn)
            items.append(bbtni)
            items.append(space)
        }
        
        // 移除最后一根弹簧
        items.removeLast()
        // 给数据源赋值
        toolBar.items = items
    }
    
    // 添加图片选择器
    private func setPictureSelectorVC() {
        
        // 添加控制器及view
        self.addChildViewController(pictureSelectorVC)
        self.view.addSubview(pictureSelectorVC.view)
        
        pictureSelectorVC.view.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(0)
        }
    }
}

/// 使用代理监听文本的输入
extension ComposeViewController: UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        // 判断是否有文本输入
        let isHas = textView.hasText()
        // 有文字就隐藏占位文本
        placeholderLabel.hidden = isHas
        // 启用“发布”按钮
        navigationItem.rightBarButtonItem?.enabled = isHas
    }
}
